package chooongg.base.activity

import android.content.Context
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.view.Window
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate
import chooongg.base.BuildConfig
import chooongg.base.QuickPageInitialize
import chooongg.base.R
import chooongg.base.annotation.*
import chooongg.base.utils.*
import chooongg.base.widget.backlayout.ParallaxBackEnable
import chooongg.base.widget.backlayout.ParallaxBackGoBackView
import chooongg.base.widget.backlayout.ParallaxBackLayout
import chooongg.base.widget.backlayout.ViewDragHelper
import chooongg.base.widget.titleBar.AbsTitleBar
import chooongg.base.widget.titleBar.CenterTitleBar

/**
 * 注意：不要直接继承QuickActivity，请自行封装Base类
 */
@ClickBlankHideKeyboard(true)
@TitleBar(true, true, CenterTitleBar::class)
@TitleBarDividerStyle(TitleBarDividerStyle.LINE)
@TitleBarDividerSupportStyle(TitleBarDividerStyle.LINE)
@ParallaxBackEnable(true)
@TranslucentStatusBar(true, true)
abstract class QuickActivity : AppCompatActivity(), QuickPageInitialize , ParallaxBackLayout.ParallaxSlideCallback{

    companion object {
        init {
            AppCompatDelegate.setCompatVectorFromResourcesEnabled(true)
        }
    }

    override fun windowBackground(): Int? = null
    protected open fun configTitleBar(titleBar: AbsTitleBar) = Unit
    override fun initConfig(savedInstanceState: Bundle?) = Unit
    override fun initContent(savedInstanceState: Bundle?) = Unit

    inline val context: Context get() = this

    inline val activity: QuickActivity get() = this

    private var isCreated = false

    var supportTitleBar: AbsTitleBar? = null
    var backLayout: ParallaxBackLayout? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        configTranslucentStatusBar4Annotation()
        configTitleBar4Annotation()
        HideKeyboardUtils.init(this)
        val contentLayout = getContentLayout() ?: return
        try {
            setContentView(contentLayout)
            getWindowBackgroundRes().apply {
                if (this == null) window.setBackgroundDrawable(null)
                else window.setBackgroundDrawableResource(this)
            }
            if (supportTitleBar != null) configTitleBar(supportTitleBar!!)
            initConfig(savedInstanceState)
            configBackLayout()
            isCreated = true
        } catch (e: Exception) {
            e.printStackTrace()
            setContentView(R.layout.activity_quick_catch)
            if (BuildConfig.DEBUG) {
                findViewById<TextView>(R.id.tv_title).text = e.message
                findViewById<TextView>(R.id.tv_message).apply {
                    text = ThrowableUtils.getFullStackTrace(e)
                    visibility = View.VISIBLE
                }
            } else {
                findViewById<TextView>(R.id.tv_title).text = "页面初始化异常"
            }
        }
    }
    private fun configBackLayout() {
        backLayout = ParallaxBackLayout(context)
        backLayout!!.attachToActivity(this)
            .setBackgroundView(ParallaxBackGoBackView(this))
            .setEdgeFlag(ViewDragHelper.EDGE_LEFT)
            .setLayoutType(ParallaxBackLayout.LAYOUT_PARALLAX)
            .setEdgeMode(ParallaxBackLayout.EDGE_MODE_EDGE)
            .setEnable(javaClass.getAnnotation(ParallaxBackEnable::class.java)?.value == true)
            .setSlideCallback(this)
    }

    override fun onDestroy() {
        backLayout = null
        super.onDestroy()
    }
    override fun onPostCreate(savedInstanceState: Bundle?) {
        super.onPostCreate(savedInstanceState)
        if (isCreated) {
            try {
                initContent(savedInstanceState)
            } catch (e: Exception) {
                e.printStackTrace()
                if (BuildConfig.DEBUG) {
                    toast(e.message)
                } else {
                    toastError("出现异常\n页面内容异常")
                }
            }
        }
    }

    private fun configTranslucentStatusBar4Annotation() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
            && javaClass.isAnnotationPresent(TranslucentStatusBar::class.java)
            && supportActionBar == null
        ) {
            val annotation = javaClass.getAnnotation(TranslucentStatusBar::class.java)!!
            if (annotation.isEnable) {
                if (annotation.isHideMask) {
                    activity.window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
                    activity.window.decorView.systemUiVisibility =
                        View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    activity.window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
                    activity.window.statusBarColor = Color.TRANSPARENT

                } else {
                    activity.window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
                }
            }
        }
    }

    private fun configTitleBar4Annotation() {
        if (javaClass.isAnnotationPresent(TitleBar::class.java) && supportActionBar == null) {
            val annotation = javaClass.getAnnotation(TitleBar::class.java)!!
            if (annotation.isShow) {
                val clazz = annotation.value
                try {
                    val constructor = clazz.java.getConstructor(Context::class.java)
                    supportTitleBar = constructor.newInstance(context)
                    supportTitleBar!!.title(loadLabel())
                    if (annotation.autoConfigBack) {
                        supportTitleBar!!.navigationGoBack()
                    }
                    val parentLayout =
                        findViewById<View>(Window.ID_ANDROID_CONTENT).parent as LinearLayout
                    parentLayout.addView(supportTitleBar, 0)
                } catch (e: Exception) {
                    Log.e(javaClass.simpleName, "Config TitleBar Exception", e)
                }
            }
        }
    }

    private val isClickBlankHideKeyboard =
        if (javaClass.isAnnotationPresent(ClickBlankHideKeyboard::class.java)) {
            javaClass.getAnnotation(ClickBlankHideKeyboard::class.java)?.value ?: false
        } else false

    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        if (isClickBlankHideKeyboard && ev.action == MotionEvent.ACTION_DOWN
            && currentFocus != null && currentFocus!!.windowToken != null
        ) {
            val v = currentFocus
            if (isShouldHideKeyboard(v, ev)) {
                val imm = getInputMethodManager()
                imm.hideSoftInputFromWindow(v!!.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
            }
        }
        return super.dispatchTouchEvent(ev)
    }

    private fun isShouldHideKeyboard(v: View?, event: MotionEvent): Boolean {
        if (v != null && v is EditText) {
            val l = intArrayOf(0, 0)
            v.getLocationOnScreen(l)
            val left = l[0]
            val top = l[1]
            val bottom = top + v.height
            val right = left + v.width
            return !(event.rawX > left && event.rawX < right && event.rawY > top && event.rawY < bottom)
        }
        return false
    }
    override fun onStateChanged(state: Int) {
        if (state == ViewDragHelper.STATE_DRAGGING) hideSoftInput(this)
    }

    override fun onPositionChanged(percent: Float) {
    }
}